package com.example.letswalk.controller;


import com.example.letswalk.pojo.ProductInfo;
import com.example.letswalk.service.ProductInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 商品信息控制层
 * author:neal
 */
@Controller
public class ProductInfoController {
//配置文件
    @Value("${file.dir}")
    private String dir;
    @Autowired
    private ProductInfoService productInfoService;

    /**
     * 商品上架
     * @param productInfo
     * @param files
     * @param request
     * @return
     */
    @RequestMapping("addProduct")
    public String addGoods(@ModelAttribute(value = "productInfo") ProductInfo productInfo, @RequestParam("files") List<MultipartFile> files, HttpServletRequest request) {
       // String rootPath = request.getScheme()+"://127.0.0.1:"+request.getServerPort()+"/download/";
        String rootPath = request.getScheme()+"://192.168.3.153:"+request.getServerPort()+"/download/";
        String productPicture = "";
        for (MultipartFile file : files) {
            String fix=file.getOriginalFilename();
            fix=fix.substring(fix.lastIndexOf(".")+1);
            String fileName = UUID.randomUUID().toString().replaceAll("-","")+"."+fix;
            String str = rootPath+fileName + ",";
            productPicture = productPicture + str;
            try {
                ProductInfoController.uploadFile(file, dir, fileName);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        productInfo.setProductPicture(productPicture);
        Date date = new Date();
        productInfo.setProductCreateTime(date);
        productInfoService.insertProductInfo(productInfo);
        return "commodity_shelves";
    }

    /**
     * 商品下架页面商品信息全局查询
     * @param model
     * @return
     */
    @RequestMapping("commodity_frame")
    public String selectProduct(Model model) {
        List<ProductInfo> list = productInfoService.selectAllProduct();
        model.addAttribute("list", list);
        model.addAttribute("count", list.size());
        return "commodity_frame";
    }

    /**
     * 商品单个下架
     * @param productName
     * @param model
     * @return
     */
    @ResponseBody
    @RequestMapping("deleteProduct")
    public List<ProductInfo> deleteProduct(@RequestParam(value = "productName") String productName, ModelMap model) {
        productInfoService.deleteProductInfo(productName);
        List<ProductInfo> list = productInfoService.selectAllProduct();
        int count = list.size();
        model.addAttribute("count", count);
        return list;
    }

    /**
     * 商品多个下架
     * @param ids
     * @param model
     * @return
     */
    @ResponseBody
    @RequestMapping("deleteProducts")
    public List<ProductInfo> deleteProducts(@RequestParam(value = "ids[]") String[] ids, ModelMap model) {
        List<String> productName = new ArrayList<>();
        for (int i = 0; i < ids.length; i++) {
            productName.add(ids[i]);
        }
        productInfoService.deleteProductsInfo(productName);
        List<ProductInfo> list = productInfoService.selectAllProduct();
        int count = list.size();
        model.addAttribute("count", count);
        model.addAttribute("list", list);
        return list;
    }

    /**
     *查找商品分区
     * @param index
     * @param modelMap
     * @return
     */
    @RequestMapping("selectRegion")
    public String selectRegion(@RequestParam("index") String index, ModelMap modelMap) {
        List<ProductInfo> list = productInfoService.selectByRegion(index);
        modelMap.addAttribute("count", list.size());
        modelMap.addAttribute("list", list);
        return "product_category";
    }
    /**
     * 修改商品信息
     * @param productInfo
     * @param modelMap
     * @return
     */
    @RequestMapping("updateProduct")
    public String updateProduct(@ModelAttribute(value = "productInfo") ProductInfo productInfo, ModelMap modelMap,List<MultipartFile> files,HttpServletRequest request) {
       // String rootPath = request.getScheme()+"://127.0.0.1:"+request.getServerPort()+"/download/";
        String rootPath = request.getScheme()+"://192.168.3.153:"+request.getServerPort()+"/download/";
        String productPicture = "";
        String format = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        Date oldDate = productInfo.getProductCreateTime();
        Date date = new Date();
        productInfo.setProductCreateTime(date);

        for (MultipartFile file : files) {
            String fix=file.getOriginalFilename();
            fix=fix.substring(fix.lastIndexOf(".")+1);
            String fileName = UUID.randomUUID().toString().replaceAll("-","")+"."+fix;
            String str = rootPath+fileName + ",";
            productPicture = productPicture + str;

            try {
                ProductInfoController.uploadFile(file, dir, fileName);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        productInfo.setProductPicture(productPicture);
        productInfoService.updateProductInfo(productInfo,oldDate);
        List<ProductInfo> list = productInfoService.selectAllProduct();
        modelMap.addAttribute("list", list);
        return "commodity_frame";
    }

    /**
     * 文件上传工具
     * @param file
     * @param filePath
     * @param fileName
     * @throws Exception
     */
    public static void uploadFile(MultipartFile file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath+fileName);
        if (!new File(filePath).exists()) {
            targetFile.mkdirs();
        }
        file.transferTo(targetFile);
    }


    @RequestMapping("/download/{url}")
    @ResponseBody
    public String down(HttpServletResponse response, @PathVariable("url") String url) throws IOException {
        File file = new File(dir+url);
        InputStream in =new FileInputStream(file);
        response.setHeader("Content-Type" ,"image/gif");
        //读入到内存
        byte bytes[] = new byte[1024];
        int n=0;
        OutputStream os =  response.getOutputStream();
        while((n=in.read(bytes))!= -1)
        {
            os.write(bytes);
        }
        os.flush();
        in.close();
        return null;
    }
}
